/*
 * SearchPanel.java
 *
 * Created on 12 September 2008, 15:54
 */

package srl.gui;

import java.awt.Color;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.Hits;
import org.jdesktop.application.Action;
import srl.corpus.CorpusConcurrencyException;
import srl.corpus.SrlDocument;

/**
 *
 * @author  john
 */
public class SearchPanel extends javax.swing.JPanel {
    
    String name;
    String query;
    /** Creates new form SearchPanel */
    public SearchPanel(String query, String name) {
        initComponents();
        this.name = name;
        this.query = query;
        Thread t = new Thread(new SearchTask(query));
        t.start();
        searchTable.getTableHeader().setResizingColumn(searchTable.getColumn("Sentence Context"));
        searchTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                if(e.getFirstIndex() == -1)
                    jButton1.setEnabled(false);
                else 
                    jButton1.setEnabled(true);
            }
        });
    }
    
    
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        searchTable = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();

        setName("Form"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        searchTable.setAutoCreateRowSorter(true);
        searchTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Document", "Sentence Number", "Sentence Context"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(srl.gui.SRLGUIApp.class).getContext().getResourceMap(SearchPanel.class);
        searchTable.setToolTipText(resourceMap.getString("searchTable.toolTipText")); // NOI18N
        searchTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_LAST_COLUMN);
        searchTable.setName("searchTable"); // NOI18N
        searchTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                searchTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(searchTable);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(srl.gui.SRLGUIApp.class).getContext().getActionMap(SearchPanel.class, this);
        jButton1.setAction(actionMap.get("viewDoc")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setEnabled(false);
        jButton1.setName("jButton1"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void searchTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_searchTableMouseClicked
        if(evt.getClickCount() == 2) {
            viewDoc();
            
        }
    }//GEN-LAST:event_searchTableMouseClicked
    
    private class SearchTask implements Runnable {
        String queryString;
        
        public SearchTask(String queryString) { this.queryString = queryString; }

        public void run() {
            try {
                Hits hits = SRLGUIApp.getApplication().proj.corpus.query(queryString);
                DefaultTableModel dtm = (DefaultTableModel)searchTable.getModel();
                dtm.setRowCount(0);
                
                if(hits.length() == 0) {
                    Object[] rowData = new Object[3];
                    rowData[0] = rowData[1] = "";
                    rowData[2] = "No matches";
                    dtm.addRow(rowData);
                    searchTable.setEnabled(false);
                }
                for(int i = 0; i < hits.length(); i++) {
                    Document d = hits.doc(i);
                    Object[] rowData = new Object[3];
                    String[] ss = d.getField("name").stringValue().split(" ");
                    rowData[0] = ss[0];
                    rowData[1] = ss[1];
                    rowData[2] = d.getField("contents").stringValue();
                    dtm.addRow(rowData);
                }
            } catch(IOException x) {
                x.printStackTrace();
                JOptionPane.showMessageDialog(SRLGUIApp.getApplication().getMainFrame(), x.getMessage(), "Search Failed", JOptionPane.ERROR_MESSAGE);
            } catch(CorpusConcurrencyException x) {
                x.printStackTrace();
                JOptionPane.showMessageDialog(SRLGUIApp.getApplication().getMainFrame(), x.getMessage(), "Search Failed", JOptionPane.ERROR_MESSAGE);
            }
        }
        
        
    }

    @Action
    public void viewDoc() {
        try {
                if(searchTable.getSelectedRow() == -1)
                    return;
                List<String> queryTokens = new LinkedList<String>();
                SrlDocument doc = new SrlDocument("null", query, SRLGUIApp.getApplication().proj.processor);
                for(Token t : doc) {
                    queryTokens.add(t.termText());
                }
                String docName = ((String)searchTable.getValueAt(searchTable.getSelectedRow(), 0));
                List<String> docSents = SRLGUIApp.getApplication().proj.corpus.getDocSentences(docName);
                TreeSet<DocHighlight> highlights = new TreeSet<DocHighlight>();
                int sentNo = 0;
                for(String sent : docSents) {
                    SrlDocument sentDoc = new SrlDocument("null",sent, SRLGUIApp.getApplication().proj.processor);
                    int i = 0;
                    for(Token t : sentDoc) {
                        if(queryTokens.contains(t.termText().toLowerCase()))
                            highlights.add(new DocHighlight(sentNo, i, i+1, Color.RED));
                        i++;
                    }
                    sentNo++;
                }
                ((SRLGUIView)SRLGUIApp.getApplication().getMainView()).openShowDocPane(docName, highlights, 
                        ShowDocPanel.TEXT, "Query " + query);
            } catch(IOException x) {
                x.printStackTrace();
            } catch(CorpusConcurrencyException x) {
                x.printStackTrace();
            }
    }

    private class ViewDocTask extends org.jdesktop.application.Task<Object, Void> {
        ViewDocTask(org.jdesktop.application.Application app) {
            // Runs on the EDT.  Copy GUI state that
            // doInBackground() depends on from parameters
            // to ViewDocTask fields, here.
            super(app);
        }
        @Override protected Object doInBackground() {
            // Your Task's code here.  This method runs
            // on a background thread, so don't reference
            // the Swing GUI from here.
            return null;  // return your result
        }
        @Override protected void succeeded(Object result) {
            // Runs on the EDT.  Update the GUI based on
            // the result computed by doInBackground().
        }
    }

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable searchTable;
    // End of variables declaration//GEN-END:variables
    
}
